<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="50">
      <el-col :span="6" v-for="(p,index) in projectList" :key="p.projectId" >
        <el-card class="card">
          <div slot="header" class="clearfix header-container">
            <div class="image-container">
              <image-preview :src="p.projectImage" :width="350" :height="200" />
            </div>
          </div>
          <div>
            <span style="font-size: 35px; font-weight: bold;">{{ p.projectName }}</span>
          </div>
          <div style="display: flex; align-items: center; justify-content: flex-end;">
            <div style="margin-left: 15px;">
              <image-preview :src="p.projectLogo" :width="50" :height="50" />
            </div>
          </div>
          <div class="progress-container" >
            <span class="progress-text">计划进度: </span>
            <el-progress :percentage="p.projectPlan" text-color="white" :text-inside="true" :stroke-width="25" color="#67C23A"></el-progress>
          </div>
          <div class="progress-container">
            <span class="progress-text">实际进度: </span>
            <el-progress :percentage="p.projectActual" text-color="white" :text-inside="true" :stroke-width="25" color="#E6A23C" ></el-progress>
          </div>
          <div>
            <el-tooltip class="item" effect="light" :content="format(p.projectTargetCost)" placement="right">
              <span class="data-span">目标成本:￥{{ formatNumber(p.projectTargetCost)}}</span>
            </el-tooltip>
          </div>
          <div>
            <el-tooltip class="item" effect="light" :content="format(p.projectPaidCost)" placement="right">
              <span class="data-span">已付成本:￥{{ formatNumber(p.projectPaidCost) }}</span>
            </el-tooltip>
          </div>
          <div>
            <span class="data-span">开业时间: {{p.projectOpeningtime}}</span>
          </div>
          <div>
            <span class="data-span">竣工时间: {{p.projectCompletetime}}</span>
          </div>
          <div style="display: flex; justify-content: space-between;">
            <div style="text-align: left;">
              <el-badge :value="p.riskCount">
                <el-button size="mini" plain type="primary" @click="openRisk(p)">风险</el-button>
              </el-badge>
            </div>
            <div style="text-align: right;">
              <el-button size="mini" plain type="warning" icon="el-icon-edit" @click="handleUpdate(p)">修改
              </el-button>
              <el-button size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete(p)">删除
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[12]"
      @pagination="getList"
    />
    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker clearable
                              v-model="form.startDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              class="date-input"
                              placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划进度" prop="projectPlan">
              <el-input v-model="form.projectPlan" placeholder="请输入计划进度">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际进度" prop="projectActual">
              <el-input v-model="form.projectActual" placeholder="请输入实际进度">
              <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开业时间" prop="projectOpeningtime">
              <el-date-picker clearable
                              v-model="form.projectOpeningtime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              class="date-input"
                              placeholder="请选择开业时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="竣工时间" prop="projectCompletetime">
              <el-date-picker clearable
                              v-model="form.projectCompletetime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              class="date-input"
                              placeholder="请选择竣工时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="目标成本" prop="projectTargetCost">
          <el-input v-model="form.projectTargetCost" placeholder="请输入目标成本" />
          <span style="margin-left: 20px; color: red">
              {{ projectTargetCostDisplay }}
          </span>
        </el-form-item>
        <el-form-item label="已付成本" prop="projectPaidCost">
          <el-input v-model="form.projectPaidCost" placeholder="请输入已付成本" />
          <span style="margin-left: 20px; color: red">
             {{ projectPaidCostDisplay }}
          </span>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="logo" prop="projectLogo">
              <image-upload v-model="form.projectLogo" :limit="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="效果图" prop="projectImage">
              <image-upload v-model="form.projectImage" :limit="1"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 风险数据模态框 -->
    <el-dialog title="风险详情" :visible.sync="dialogTableVisible">
      <el-table :data="riskData">
        <el-table-column property="riskId" label="序号"></el-table-column>
        <el-table-column property="risktypeName" label="风险类别"></el-table-column>
        <el-table-column property="riskTitle" label="风险标题"></el-table-column>
        <el-table-column property="nickName" label="跟进人"></el-table-column>
        <el-table-column property="riskContent" label="内容"></el-table-column>
        <el-table-column prop="riskStatus" label="状态" width="200">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.riskStatus===1" type="danger">待跟进</el-tag>
            <el-tag v-if="scope.row.riskStatus===2" type="primary">跟进中</el-tag>
            <el-tag v-if="scope.row.riskStatus===3" type="success">已解决</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject,getRisk } from "@/api/project/project";

export default {
  name: "Project",
  data() {
    return {
      projectTargetCostDisplay: '',
      projectPaidCostDisplay: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        projectName: null,
        projectPlan: null,
        projectActual: null,
        startDate: null,
        projectOpeningtime: null,
        projectCompletetime: null,
        projectTargetCost: null,
        projectPaidCost: null,
        projectLogo: null,
        projectImage: null,
        riskCount: null,
      },
      // 表单参数
      form: {},
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        projectPlan: [
          { required: true, message: "计划进度不能为空", trigger: "blur" }
        ],
        projectActual: [
          { required: true, message: "实际进度不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        projectOpeningtime: [
          { required: true, message: "开业时间不能为空", trigger: "blur" }
        ],
        projectCompletetime: [
          { required: true, message: "竣工时间不能为空", trigger: "blur" }
        ],
        projectTargetCost: [
          { required: true, message: "目标成本不能为空", trigger: "blur" }
        ],
        projectPaidCost: [
          { required: true, message: "已付成本不能为空", trigger: "blur" }
        ],
        projectLogo: [
          { required: true, message: "logo不能为空", trigger: "blur" }
        ],
        projectImage: [
          { required: true, message: "效果图不能为空", trigger: "blur" }
        ],
      },
      //风险模态框
      dialogTableVisible: false,
      //风险数据
      riskData: [],
    };
  },
  created() {
    this.getList();
  },
  watch: {
    'form.projectTargetCost': function (newVal) {
      this.projectTargetCostDisplay='';
      this.formatCurrency('projectTargetCostDisplay', newVal);
    },
    'form.projectPaidCost': function (newVal) {
      this.projectPaidCostDisplay='';
      this.formatCurrency('projectPaidCostDisplay', newVal);
    }
  },
  methods: {
    // 格式化单位
    format(value) {
      if (value !== '' && value != null && !isNaN(value)) {
        value = parseFloat(value);
        let unit;
        if (value >= 100000000) {
          unit ='亿元';
        } else if (value >= 10000) {
          unit ='万元';
        } else if (value > 0) {
          unit ='元';
        }return unit;
      } else {
        return '';
      }
    },
    // 表单中的输入框输入数字时，自动转换
    formatCurrency(field, value) {
      if (value !== '' && value != null && !isNaN(value)) {
        value = parseFloat(value);
        let formattedValue;
        if (value >= 100000000) {
          formattedValue = '约' + (value / 100000000).toFixed(2) + '亿元';
        } else if (value >= 10000) {
          formattedValue = '约' + (value / 10000).toFixed(2) + '万元';
        } else if (value > 0) {
          formattedValue = '约' + value.toFixed(2) + '元';
        }
        // 更新显示的值 更新给对应字段
          this[field] = formattedValue;
        }
    },
    openRisk(p){
      getRisk(p.projectId).then(response => {
        this.dialogTableVisible = true;
        this.riskData = response.data;
      });
    },
    // 数字格式化 返回一个格式化后的字符串
    formatNumber(number) {
      return new Intl.NumberFormat('en-US',
        { minimumFractionDigits: 2, maximumFractionDigits: 2 })
        .format(number);
    },
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        projectPlan: null,
        projectActual: null,
        startDate: null,
        projectOpeningtime: null,
        projectCompletetime: null,
        projectTargetCost: null,
        projectPaidCost: null,
        projectLogo: null,
        projectImage: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    /** 修改按钮操作 */
    handleUpdate(p) {
      this.reset();
      const projectId = p.projectId || this.ids
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(p) {
      const projectIds = p.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？').then(function() {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.card {
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
}
.data-span {
  line-height: 38px;
}
.date-input >>> .el-input__inner {
  width: 350px;
  height: 36px;
}
.header-container {
  display: flex;
  align-items: center;
  padding: 2px;
}

</style>
